package org.xlp.base.application.handler;

import org.xlp.base.application.constant.ApplicationConst;
import org.xlp.base.application.util.ApplicationUtils;
import org.xlp.db.xml.AbstractSQLXmlFileHandler;
import org.xlp.db.xml.ISQLXmlFileHandlerChain;
import org.xlp.db.xml.SQLXmlFileParseException;

import java.io.*;

public class ApplicationHomeSQLXmlFileHandler extends AbstractSQLXmlFileHandler {
    /**
     * 文件名前缀
     */
    private final static String FILE_PATH_PREFIX = ApplicationConst.CONFIG_BASE_DIR_PRE;

    /**
     * 把指定的文件描述路径转换成文件输入流
     *
     * @param sqlXmlFilePath
     * @return
     * @throws SQLXmlFileParseException 假如文件解析失败，则抛出该异常
     */
    @Override
    protected InputStream toInputStream(String sqlXmlFilePath) {
        sqlXmlFilePath = sqlXmlFilePath.substring(FILE_PATH_PREFIX.length());
        File file = new File(ApplicationUtils.getConfigBaseDir(), sqlXmlFilePath);
        try {
            return new BufferedInputStream(new FileInputStream(file));
        } catch (FileNotFoundException e) {
            throw new SQLXmlFileParseException(e);
        }
    }

    /**
     * 判断给定的路径是否符合该sql配置文件解析器，进行解析
     *
     * @param sqlXmlFilePath
     * @return 返回 true：该解析器进行解析，false：则不进行解析，交给下一个解析器去解析
     * @see AbstractSQLXmlFileHandler#handle(String, ISQLXmlFileHandlerChain)
     */
    @Override
    protected boolean match(String sqlXmlFilePath) {
        return super.match(sqlXmlFilePath)
                && sqlXmlFilePath.startsWith(FILE_PATH_PREFIX);
    }
}
